package com.carbohydrate42.kotlin_compose_demo.compose

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import java.util.concurrent.TimeUnit

fun getWsClient(
    onChange: (text: String) -> Unit = {}
): WebSocket {
    return OkHttpClient().newBuilder()
        .pingInterval(10, TimeUnit.SECONDS)
        .build()
        .newWebSocket(
            Request.Builder()
                .url("ws://192.168.0.101:6666/websocket")
                .build(),
            object : WebSocketListener() {
                override fun onOpen(webSocket: WebSocket, response: Response) {
                    // 连接成功回调
                    onChange("session open : ${response.code}")
                }

                override fun onMessage(webSocket: WebSocket, text: String) {
                    // 接收到消息回调
                    onChange("receive message : $text")
                }

                override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
                    // 连接关闭回调
                    onChange("onClosing : $reason")
                }

                override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
                    // 连接失败回调
                    t.printStackTrace()
                    onChange("connect fail : ${t.message}")
                }
            }
        )
}

@Composable
@Preview(showSystemUi = true, showBackground = true)
fun TryWebSocket() {

    val msgList = remember {
        mutableStateListOf<String>()
    }

    val ws = remember {
        mutableStateOf<WebSocket?>(null)
    }

    Column(
        modifier = Modifier.fillMaxSize()
    ) {
        Button(onClick = {
            ws.value = getWsClient {
                msgList.add(it)
            }
        }) {
            Text(text = "connect")
        }
        msgList.forEach {
            Text(text = it)
        }
    }
}